package com.ruoyi.web.controller.system;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.domain.model.SmsLoginBody;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.Md5Util;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.vo.RouterVo;
import com.ruoyi.system.service.ISysMenuService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.SysLoginService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotBlank;
import java.util.*;

/**
 * 登录验证
 *
 * @author Lion Li
 */
@Validated
@RequiredArgsConstructor
@RestController
public class SysLoginController {

    private final SysLoginService loginService;
    private final ISysMenuService menuService;
    private final ISysUserService userService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @SaIgnore
    @PostMapping("/login")
    public R<Map<String, Object>> login(@RequestBody LoginBody loginBody) {
        Map<String, Object> ajax = new HashMap<>();
        // 生成令牌
        // 解密
        JSONObject jsonObject;
        try {
            String stringJson = new String(Base64.getDecoder().decode(loginBody.getData()));
            jsonObject = JSON.parseObject(stringJson);
        } catch (Exception e) {
            throw new RuntimeException("登录失败");
        }
        if (StringUtils.isBlank(jsonObject.getString("username"))) {
            throw new RuntimeException("用户名不能为空");
        }
        if (StringUtils.isBlank(jsonObject.getString("password"))) {
            throw new RuntimeException("密码不能为空");
        }
        if (StringUtils.isBlank(jsonObject.getString("code"))) {
            throw new RuntimeException("验证码不能为空");
        }
        loginBody.setUsername(jsonObject.getString("username"));
        loginBody.setPassword(jsonObject.getString("password"));
        loginBody.setCode(jsonObject.getString("code"));
        loginBody.setUuid(jsonObject.getString("uuid"));

        String token = loginService.login(loginBody.getUsername(), Md5Util.encrypt3ToMD5(loginBody.getPassword()), loginBody.getCode(), loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return R.ok(ajax);
    }

    /**
     * 短信登录(示例)
     *
     * @param smsLoginBody 登录信息
     * @return 结果
     */
    @SaIgnore
    @PostMapping("/smsLogin")
    public R<Map<String, Object>> smsLogin(@Validated @RequestBody SmsLoginBody smsLoginBody) {
        Map<String, Object> ajax = new HashMap<>();
        // 生成令牌
        String token = loginService.smsLogin(smsLoginBody.getPhonenumber(), smsLoginBody.getSmsCode());
        ajax.put(Constants.TOKEN, token);
        return R.ok(ajax);
    }

    /**
     * 小程序登录(示例)
     *
     * @param xcxCode 小程序code
     * @return 结果
     */
    @SaIgnore
    @PostMapping("/xcxLogin")
    public R<Map<String, Object>> xcxLogin(@NotBlank(message = "{xcx.code.not.blank}") String xcxCode) {
        Map<String, Object> ajax = new HashMap<>();
        // 生成令牌
        String token = loginService.xcxLogin(xcxCode);
        ajax.put(Constants.TOKEN, token);
        return R.ok(ajax);
    }

    /**
     * 退出登录
     */
    @SaIgnore
    @PostMapping("/logout")
    public R<Void> logout() {
        loginService.logout();
        return R.ok("退出成功");
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public R<Map<String, Object>> getInfo() {
        LoginUser loginUser = LoginHelper.getLoginUser();
        SysUser user = userService.selectUserById(loginUser.getUserId());
        Map<String, Object> ajax = new HashMap<>();
        ajax.put("user", user);
        ajax.put("roles", loginUser.getRolePermission());
        ajax.put("permissions", loginUser.getMenuPermission());
        return R.ok(ajax);
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public R<List<RouterVo>> getRouters() {
        Long userId = LoginHelper.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return R.ok(menuService.buildMenus(menus));
    }

    /**
     * 获取app菜单
     *
     * @return 菜单列表
     */
    @GetMapping("getAppMenus")
    public R<List<String>> getAppMenus() {
        Long userId = LoginHelper.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        List<String> menuList = new ArrayList<>();
        if (CollUtil.isNotEmpty(menus)) {
            for (SysMenu menu : menus) {
                if ("report".equals(menu.getPath())) {
                    menuList.add(menu.getMenuName());
                    continue;
                }
                if ("risk".equals(menu.getPath())) {
                    List<SysMenu> childrenList = menu.getChildren();
                    if (CollUtil.isNotEmpty(childrenList)) {
                        for (SysMenu sysMenu : childrenList) {
                            if ("plan".equals(sysMenu.getPath())) {
                                menuList.add(sysMenu.getMenuName());
                                continue;
                            }
                            if ("meeting".equals(sysMenu.getPath())) {
                                menuList.add(sysMenu.getMenuName());
                                continue;
                            }
                            if ("check-post".equals(sysMenu.getPath())) {
                                menuList.add(sysMenu.getMenuName());
                                continue;
                            }
                            if ("check-one-shot-job".equals(sysMenu.getPath())) {
                                menuList.add(sysMenu.getMenuName());
                                continue;
                            }
                            if ("riskrouth".equals(sysMenu.getPath())) {
                                List<SysMenu> riskList = sysMenu.getChildren();
                                if (CollUtil.isNotEmpty(riskList)) {
                                    for (SysMenu riskMenu : riskList) {
                                        if ("hidden-danger/rectification".equals(riskMenu.getPath())) {
                                            menuList.add(riskMenu.getMenuName());
                                            continue;
                                        }
                                        if ("hidden-danger/inspect".equals(riskMenu.getPath())) {
                                            menuList.add(riskMenu.getMenuName());
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return R.ok(menuList);
    }
}
